package com.gusto.engine.semsim.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.gusto.engine.semsim.exceptions.ConfigException;
import com.gusto.engine.semsim.measures.ResourceSimilarity;

/**
 * <p>Utilities for processing the configFile, 
 * that will contain the hash code of the similarities.<br/>
 * Contains methods for loading and saving configFile, 
 * and for checking if any definition has changed in it.</p>
 * 
 * @author amokrane.belloui@gmail.com
 *
 */
public class ConfigUtils {
	
	private Logger log = Logger.getLogger(getClass());
	
	/**
	 * Configuration file that will store hash codes of the similarity measures.
	 */
	protected String configFile = null;
	public void setConfigFile(String configFile) {
		this.configFile = configFile;
	}
	public String getConfigFile() {
		return configFile;
	}
	
	private Properties props;
	private boolean propertiesLoaded = false;
	
	public void loadProperties() throws ConfigException {
		props = new Properties();
		try {
			props.load(new FileInputStream(new File(configFile)));
			log.debug("Loading similarities config file : '" + configFile + "'");
			propertiesLoaded = true;
		}
		catch (Exception e) {
			log.warn("Cannot find config file '" + configFile + "', " +
					 "copy your configuration file or create a new one");
			throw new ConfigException("Cannot find config file '" + configFile + "', " +
					                  "copy your configuration file or create a new one, to the folder " + new File("").getAbsolutePath());
		}
	}
	
	public void saveProperties() throws ConfigException {
		// Save new Values to config file
		try {
			props.store(new FileOutputStream(new File(configFile)), "utf-8");
			log.warn("Saving similarities config file : '" + configFile + "'");
		}
		catch (Exception e) {
			throw new ConfigException("Error in saving config file, distances will be reinitialized next check", e);
		}
	}
	
	public boolean checkDefinitionChanged(String context, ResourceSimilarity resourceSimilarity) throws ConfigException {
		if (! propertiesLoaded) {
			throw new ConfigException("You must load properties .loadProperties() before checking definition change");
		}
		boolean hasChanged = false;
		// Old Hash from configFile
		String oldHash = (String)props.get(context);
		// New Hash from configFile
		//String newHash = resourceSimilarity.getId().hashCode() + "";
		String newHash = resourceSimilarity.getId() + "";
		log.debug("Old Id, '" + context + "' " + oldHash);
		log.debug("New Id, '" + context + "' " + newHash);
		hasChanged = (oldHash != null ? !oldHash.equals(newHash) : false);
		if (hasChanged) {
			log.debug("Context '" + context + "' has changed");
		}
		props.put(context, newHash);
		return hasChanged;
	}
	
}
